package com.jackrain.nea.clould.dao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Hashtable;

/**
 * 查询key
 */
@Slf4j
@Component
public class StoreKeyDao {


    private static final String secret_key = "secret";
    private static final String appkey_key = "appkey";
    private static final String sessionkey_key = "sessionkey";

    private Hashtable<String, String> hashtable = new Hashtable<String, String>();


    public String getSecret(String plantNO, String storeNick) throws Exception {

        if (!hashtable.containsKey(plantNO + storeNick + secret_key)) {
            queryMqKey(plantNO, storeNick);
        }
        return hashtable.get(plantNO + storeNick + secret_key);
    }

    public String getAppKey(String plantNO, String storeNick) throws Exception {

        if (!hashtable.containsKey(plantNO + storeNick + appkey_key)) {
            queryMqKey(plantNO, storeNick);
        }
        return hashtable.get(plantNO + storeNick + appkey_key);
    }

    public String getSessionKey(String plantNO, String storeNick) throws Exception {

        if (!hashtable.containsKey(plantNO + storeNick + sessionkey_key)) {
            queryMqKey(plantNO, storeNick);
        }
        return hashtable.get(plantNO + storeNick + sessionkey_key);
    }


    /**
     * 查询mqkey
     *
     * @param plantNO
     * @param storeNick
     * @return
     * @throws Exception
     */
    public JSONArray queryMqKey(String plantNO, String storeNick) throws Exception {

        String sql = "select secret, appkey,sessionkey" +
                " from oms_storekey,oms_store,oms_plant" +
                " where oms_storekey.OMS_STOREID =  oms_store.ID" +
                " and oms_plant.id = oms_store.PLANTTYPE_ID" +
                " and oms_plant.NO = ? " +
                " and oms_store.NICKNAME = ?";

        JSONArray resultArr = QueryEngine.getInstance().doQueryObjectArray(sql, new Object[]{plantNO, storeNick});

        handleMqKey(resultArr, plantNO, storeNick);

        return resultArr;
    }

    private void handleMqKey(JSONArray resultArr, String plantNO, String storeNick) {

        if (resultArr == null || resultArr.size() <= 0) {
            return;
        }

        JSONObject resultObject = resultArr.getJSONObject(0);
        String secret = resultObject.getString("secret");
        String appkey = resultObject.getString("appkey");
        String sessionkey = resultObject.getString("sessionkey");


        hashtable.put(plantNO + storeNick + secret_key, secret);
        hashtable.put(plantNO + storeNick + appkey_key, appkey);
        hashtable.put(plantNO + storeNick + sessionkey_key, sessionkey);

    }


}
